package pers.zc.activiti.utils;

import org.activiti.bpmn.model.Artifact;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.IdentityLinkEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * @desc 针对流程管理的工具类
 **/
@Component("activitiUtils")
public class ActivitiUtils {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "processEngine")
    private ProcessEngine processEngine;

    /**
     * 部署流程
     *
     * @param processName 流程的名字
     */
    public void deployeProcess(String processName) {
        this.processEngine.getRepositoryService()
                .createDeployment()
                .name(processName)
                .addClasspathResource("process/" + processName + ".png")
                .addClasspathResource("process/" + processName + ".bpmn")
                .deploy();
        logger.debug("部署流程成功！");
    }

    /**
     * 部署流程
     *
     * @param file        流程的zip文件
     * @param processName 流程的名字
     */
    public void deployeProcess(File file, String processName){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        this.processEngine.getRepositoryService()
                .createDeployment()
                .name(processName)
                .addZipInputStream(zipInputStream)
                .deploy();
        logger.debug("部署流程成功！");
    }

    /**
     * 部署流程
     *
     * @param inputStream
     * @param processName
     */
    public void deployeProcess(InputStream inputStream, String processName) {
        this.processEngine.getRepositoryService()
                .createDeployment()
                .name(processName)
                .addInputStream(processName + ".bpmn", inputStream)
                .deploy();
        logger.debug("部署流程成功！");
    }


    /**
     * 查询所有的部署流程
     *
     * @return
     */
    public List<Deployment> getAllDeplyoment() {
        return this.processEngine.getRepositoryService()
                .createDeploymentQuery()
                .orderByDeploymenTime()
                .desc()
                .list();
    }

    /**
     * 查询所有的部署定义信息
     *
     * @return
     */
    public List<ProcessDefinition> getAllProcessInstance() {
        return this.processEngine.getRepositoryService()
                .createProcessDefinitionQuery()
                .orderByProcessDefinitionVersion()
                .desc()
                .list();
    }

    /**
     * 根据部署ID，来删除部署
     *
     * @param deplyomenId
     */
    public void deleteDeplyomentByPID(String deplyomenId) {
        this.processEngine.getRepositoryService()
                .deleteDeployment(deplyomenId, true);
    }

    /**
     * 查询某个部署流程的流程图
     *
     * @param pid
     * @return
     */
    public InputStream lookProcessPicture(String pid) {
        return this.processEngine.getRepositoryService()
                .getProcessDiagram(pid);
    }

    /**
     * 开启流程实例
     *
     * @param key
     * @param variables
     */
    public ProcessInstance startProceesInstance(String key, Map<String, Object> variables) {
        ProcessInstance processInstance = this.processEngine.getRuntimeService()
                .startProcessInstanceByKey(key, variables); //第一个参数，就是流程中自己定义的名字，这个一定要匹配，否则是找不到的。
        return  processInstance;
    }

    /**
     * 开启流程实例
     * @param key
     * @param businessKey 业务外检key
     * @param userId
     */
    public void startProceesInstance(String key, String businessKey ,String userId) {
        Map<String, Object> variables = new HashMap<>();
        variables.put("userID", userId);
        this.processEngine.getRuntimeService()
                .startProcessInstanceByKey(key, businessKey, variables); //第一个参数，就是流程中自己定义的名字，这个一定要匹配，否则是找不到的。
    }

    /**
     * 查询当前登陆人的所有任务
     *
     * @param userId
     * @return
     */
    public List<Task> queryCurretUserTaskByAssignerr(String userId,int pageNum ,int pageSize) {
       return this.processEngine.getTaskService()
                .createTaskQuery()
                .taskAssignee(userId)
                .orderByTaskCreateTime()
                .desc()
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
    }
    /**
     * 查询当前登陆人的所有已办完结任务
     *
     * @param userId
     * @return
     */
    public List<HistoricTaskInstance> queryHistoryUserTaskByAssignerrFinished(String userId,int pageNum ,int pageSize) {
        return this.processEngine.getHistoryService().createHistoricTaskInstanceQuery()
                .taskAssignee(userId)
                .finished()
                .orderByTaskCreateTime()
                .desc()
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
    }
    /**
     * 查询当前登陆人的所有已办完未结任务
     *
     * @param userId
     * @return
     */
    public List<HistoricTaskInstance> queryHistoryUserTaskByAssignerrUnfinished(String userId,int pageNum ,int pageSize) {
        return this.processEngine.getHistoryService().createHistoricTaskInstanceQuery()
                .taskAssignee(userId)
                .unfinished()
                .orderByTaskCreateTime()
                .desc()
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
    }

    /**
     * 已完结流程实例活动列表
     * @param processInstanceId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public  List<HistoricActivityInstance> historyActInstanceListFinished(String processInstanceId,int pageNum ,int pageSize) {
        return this.processEngine.getHistoryService()
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .finished()
                .orderByHistoricActivityInstanceStartTime()
                .desc()
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
    }

    /**
     * 未完结流程实例活动列表
     * @param processInstanceId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public  List<HistoricActivityInstance> historyActInstanceListUnfinished(String processInstanceId,int pageNum ,int pageSize) {
        return this.processEngine.getHistoryService()
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .unfinished()
                .orderByHistoricActivityInstanceStartTime()
                .desc()
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
    }
    /**
     * 根据TaskId，获取到当前的执行节点实例对象
     *
     * @param taskId
     * @return
     */
    /*public ActivityImpl getActivityImplByTaskId(String taskId) {
        //首先得到任务
        Task task = this.getTaskByTaskId(taskId);
        //其次，得到流程实例
        ProcessInstance processInstance = this.getProcessInstanceByTask(task);
        //再次，根据流程实例来获取到流程定义
        ProcessDefinitionEntity processDefinitionEntity = this.getProcessDefinitionEntityByTask(task);
        //再根据，流程定义，通过流程实例中来获取到activiti的ID，从而得到acitviImp
        ActivityImpl activity = processDefinitionEntity.findActivity(processInstance.getActivityId());
        return activity;
    }*/

    /**
     * 根据taskId，判断对应的流程实例是否结束
     * 如果结束了，那么得到的流程实例就是返回一个null
     * 否则就是返回对应的流程实例对象
     * 当然也可以选择返回boolean类型的
     *
     * @param taskId 任务ID
     * @return
     */
    public ProcessInstance isFinishProcessInstancs(String taskId) {
        //1,先根据taskid，得到任务
        Task task = getTaskByTaskId(taskId);
        //2:完成当前任务
        finishCurrentTaskByTaskId(taskId);
        //3:得到当前任务对应得的流程实例对象
        ProcessInstance processInstance = getProcessInstanceByTask(task);
        return processInstance;
    }

    /**
     * 获取当前执行节点的所有出口
     *
     * @param
     * @return
     */
    /*public List<PvmTransition> getCurrentActivitiImplPvm(ActivityImpl activity) {
        List<PvmTransition> outgoingTransitions = activity.getOutgoingTransitions();
        return outgoingTransitions;
    }

    /**
     * 根据taskId获取到task
     *
     * @param taskId
     * @return
     */
    public Task getTaskByTaskId(String taskId) {
        //得到当前的任务
        Task task = this.processEngine.getTaskService()
                .createTaskQuery()
                .taskId(taskId)
                .singleResult();
        return task;
    }

    /**
     * 根据Task中的流程实例的ID，来获取对应的流程实例
     *
     * @param task 流程中的任务
     * @return
     */
    public ProcessInstance getProcessInstanceByTask(Task task) {
        //得到当前任务的流程
        ProcessInstance processInstance = this.processEngine.getRuntimeService()
                .createProcessInstanceQuery()
                .processInstanceId(task.getProcessInstanceId())
                .singleResult();
        processInstance.getBusinessKey();
        return processInstance;
    }

    /**
     * 根据Task来获取对应的流程定义信息
     *
     * @param task
     * @return
     */
    public ProcessDefinitionEntity getProcessDefinitionEntityByTask(Task task) {
        ProcessDefinitionEntity processDefinitionEntity = (ProcessDefinitionEntity) this.processEngine.getRepositoryService()
                .getProcessDefinition(task.getProcessDefinitionId());
        return processDefinitionEntity;
    }

    /**
     * 根据taskId获取到businesskey，这个值是管理activiti表和自己流程业务表的关键之处
     *
     * @param taskId 任务的ID
     * @return
     */
    public String getBusinessKeyByTaskId(String taskId) {
        Task task = this.getTaskByTaskId(taskId);
        ProcessInstance processInstance = this.getProcessInstanceByTask(task);
        //返回值
        return processInstance.getBusinessKey();
    }

    /**
     * 根据taskId，完成任务
     *
     * @param taskId
     */
    public void finishCurrentTaskByTaskId(String taskId) {
        this.processEngine.getTaskService().complete(taskId);
    }

    /**
     * 完成任务的同时，进行下一个节点的审批人员的信息的传递
     *
     * @param taskId
     * @param variables
     */
    public void finishCurrentTaskByTaskId(String taskId, Map<String, Object> variables) {
        this.processEngine.getTaskService().complete(taskId, variables);
    }

    /**
     * 查询用户可选流程任务
     * @param userId
     * @param pageNum
     * @param pageSize
     * @return
     */
    public List<Task> queryCurretUserTaskByCandidate(String userId, int pageNum, int pageSize) {
        List<Task> taskList = this.processEngine.getTaskService()
                .createTaskQuery()
                .taskCandidateUser(userId)
                .listPage(pageNum==0 || pageNum == 1 ? 0 : (pageNum-1) * pageSize,pageSize);
        return taskList;
    }

    /**
     * 认领某个任务
     * @param taskId
     * @param userId
     */
    public void claimTask(String taskId, String userId) {
        this.processEngine.getTaskService().claim(taskId,userId);
    }

    public void findNextTaskDefinition(String taskId) {
       /* Task task = this.getTaskByTaskId(taskId);
        BpmnModel bpmnModel = this.processEngine.getRepositoryService().getBpmnModel(task.getProcessDefinitionId());
        Collection<FlowElement> flowElements  =  bpmnModel.getMainProcess().getFlowElements();

        String excId = task.getExecutionId();
        ExecutionEntity execution = (ExecutionEntity) this.processEngine.getRuntimeService().createExecutionQuery().executionId(excId).singleResult();
        String activitiId = execution.getActivityId();

        for(FlowElement f : flowElements){

        }*/
    }
}
